<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="queryForm" :inline="true" :model="queryParams" size="small">
        <el-form-item prop="params.name">
          <el-input
            v-model="queryParams.params.name"
            class="filter-item"
            clearable
            placeholder="班级名称"
            style="width: 150px;"
          />
        </el-form-item>
        <el-form-item prop="params.director">
          <el-select
            v-model="queryParams.params.director"
            class="filter-item"
            clearable
            placeholder="班级主任"
            style="width: 150px;"
          >
            <el-option v-for="item in directorList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- 按钮 -->
        <el-button
          v-permission="['/information/classes/search']"
          v-waves
          class="filter-item"
          icon="el-icon-search"
          size="small"
          style="margin-left: 10px;"
          type="primary"
          @click="getDataList"
        >查询
        </el-button>
        <el-button
          v-permission="['/information/classes/add']"
          v-waves
          class="filter-item"
          icon="el-icon-plus"
          size="small"
          type="primary"
          @click="handleOpenDialog('add')"
        >新增
        </el-button>
        <el-button
          v-permission="['/information/classes/search']"
          v-waves
          class="filter-item"
          icon="el-icon-refresh"
          size="small"
          type="primary"
          @click="resetQueryForm"
        >重置
        </el-button>
      </el-form>
    </div>
    <!-- 数据表格 -->
    <el-table
      v-loading="dataListLoading"
      :data="dataList"
      border
      data-list
      fit
      highlight-current-row
      size="small"
      style="width: 100%;"
    >
      <el-table-column :index="shownIndex" align="center" fixed label="序号" type="index" />
      <el-table-column align="center" label="班级名称" prop="name" show-overflow-tooltip />
      <el-table-column align="center" label="年级名称" prop="gradeName" show-overflow-tooltip />
      <el-table-column align="center" label="班主任" prop="directorName" show-overflow-tooltip />
      <el-table-column align="center" label="邮箱" prop="email" show-overflow-tooltip />
      <el-table-column align="center" label="电话" prop="phone" show-overflow-tooltip />
      <el-table-column align="center" label="创建人" prop="creatorName" show-overflow-tooltip />
      <el-table-column align="center" label="创建时间" prop="createdDate" show-overflow-tooltip sortable="custom" />
      <el-table-column align="center" label="修改时间" prop="modifiedDate" show-overflow-tooltip sortable="custom" />
      <el-table-column align="center" label="备注" prop="remark" show-overflow-tooltip />
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="250">
        <template slot-scope="scope">
          <el-button
            v-permission="['/information/classes/add']"
            v-waves
            size="mini"
            type="success"
            @click="handleOpenDialog('addTeacher', scope.row)"
          >新增教师
          </el-button>
          <el-button
            v-permission="['/information/classes/update']"
            v-waves
            size="mini"
            type="primary"
            @click="handleOpenDialog('update', scope.row)"
          >编辑
          </el-button>
          <el-button
            v-permission="['/information/classes/delete']"
            v-waves
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.size"
        :page-sizes="[10,20,30, 50]"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!--新增/编辑对话框    -->
    <el-dialog
      v-loading="dialogLoading"
      :close-on-click-modal="false"
      :title="dialogTitleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      element-loading-text="保存中"
    >
      <el-form
        ref="dataForm"
        :model="dataForm"
        :rules="rules"
        label-position="right"
        size="small"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="班级名称：" prop="name">
              <el-input v-model="dataForm.name" :readonly="formReadOnly" placeholder="年级名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所在年级：" prop="director">
              <el-select v-model="dataForm.gradeId" :disabled="formReadOnly" filterable placeholder="请选择">
                <el-option v-for="item in gradeList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="班级主任：" prop="director">
              <el-select v-model="dataForm.director" :disabled="formReadOnly" filterable placeholder="请选择">
                <el-option v-for="item in directorList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="咨询邮箱" prop="email">
              <el-input v-model="dataForm.email" :readonly="formReadOnly" placeholder="咨询邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="咨询电话" prop="phone">
              <el-input v-model="dataForm.phone" :readonly="formReadOnly" placeholder="咨询电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="dataForm.remark" :readonly="formReadOnly" placeholder="备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <div v-show="formReadOnly">
          <el-divider content-position="center">新增教师</el-divider>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="选择教师：" prop="director">
                <el-select v-model="teacherClasses.teacherId" filterable placeholder="请选择">
                  <el-option v-for="item in teacherList" :key="item.id" :label="item.name" :value="item.id">
                    <span style="float: left">{{ item.name }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.positionName }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <el-table
        v-show="formReadOnly"
        v-loading="dataListLoading"
        :data="teacherClassesList"
        border
        data-list
        fit
        highlight-current-row
        max-height="300px"
        size="small"
        style="width: 100%;"
      >
        <el-table-column :index="shownIndex" align="center" fixed label="序号" type="index" />
        <el-table-column align="center" label="教师名称" prop="name" show-overflow-tooltip />
        <el-table-column align="center" label="性别" prop="sexName" show-overflow-tooltip />
        <el-table-column align="center" label="教师职位" prop="positionName" show-overflow-tooltip />
        <el-table-column align="center" label="教师年龄" prop="age" show-overflow-tooltip />
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="250">
          <template slot-scope="scope">
            <el-button
              v-waves
              size="mini"
              type="danger"
              @click="handleTeacherDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus==='add'" size="small" type="primary" @click="handleAdd">确定</el-button>
        <el-button v-if="dialogStatus==='update'" size="small" type="primary" @click="handleUpdate">确定</el-button>
        <el-button v-if="dialogStatus==='addTeacher'" size="small" sty type="primary" @click="handleAddTeacher">新增教师
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import { add, addTeacherClasses, del, fetchList, update } from '@/api/information/classes'
import { delTeacherClasses, findByObject, findListByClassesId } from '@/api/information/teacher'
import { findByObject as findGradeList } from '@/api/information/grade'

export default {
  name: 'Classes',
  data() {
    return {
      total: 0,
      dataList: [],
      teacherList: [],
      gradeList: [],
      teacherClassesList: [],
      dataListLoading: false,
      dialogFormVisible: false,
      dialogLoading: false,
      dialogStatus: '',
      dialogTitleMap: {
        add: '新增',
        update: '编辑',
        addTeacher: '新增教师'
      },
      teacherClasses: {
        teacherId: '',
        classesId: ''
      },
      queryParams: {
        page: 1,
        size: 10,
        params: {
          name: '',
          director: ''
        }
      },
      dataForm: {
        name: '',
        gradeId: '',
        director: '',
        email: '',
        phone: '',
        remark: ''
      },
      rules: {
        name: [{ required: true, message: '年级名称不能为空', trigger: 'change' }],
        gradeId: [{ required: true, message: '所属年级不能为空', trigger: 'change' }],
        director: [{ required: true, message: '班主任不能为空', trigger: 'change' }]
      }
    }
  },
  computed: {
    formReadOnly() {
      return this.dialogStatus === 'addTeacher'
    },
    directorList() {
      return this.teacherList.filter(r => {
        return r.positionRank === 1
      })
    }
  },
  mounted() {
    this.getDataList()
    // 获取年级名称
    findGradeList({}).then(res => {
      this.gradeList = res.data
    })
    // 获取教师
    findByObject({}).then(res => {
      this.teacherList = res.data
    })
  },
  methods: {
    shownIndex(index) {
      return (this.queryParams.page - 1) * this.queryParams.size + index + 1
    },
    getDataList() {
      this.dataListLoading = false
      fetchList(this.queryParams)
        .then(res => {
          console.log(res)
          this.dataList = res.data.records
          this.total = res.data.total
          this.dataListLoading = false
        })
        .catch(err => {
          console.log(err)
          this.dataLoading = false
        })
    },
    getTeacherClasses() {
      findListByClassesId(this.dataForm.id).then(res => {
        this.teacherClassesList = res.data
      })
    },
    handleOpenDialog(type, rowData) {
      this.resetDataForm()
      this.dialogStatus = type
      this.dialogFormVisible = true
      if (type !== 'delete') {
        this.dataForm = JSON.parse(JSON.stringify(rowData))
      }
      if (type === 'addTeacher') {
        this.getTeacherClasses()
      }
    },
    resetQueryForm() {
      this.$refs['queryForm'].resetFields()
      this.queryParams.page = 1
      this.getDataList()
    },
    resetDataForm() {
      if (this.$refs['dataForm']) {
        // 由于编辑数据的时候会导致表单对象的初始化值发生变更，所以在重置表单前先手动重置表单对象的值
        this.dataForm = {
          name: '',
          director: '',
          email: '',
          phone: '',
          remark: ''
        }
        this.$refs['dataForm'].resetFields()
      }
    },
    handleSizeChange(size) {
      this.queryParams.size = size
      this.getDataList()
    },
    handleCurrentChange(page) {
      this.queryParams.page = page
      this.getDataList()
    },
    handleAdd() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dialogLoading = true
          add(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '新增成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleAddTeacher() {
      this.teacherClasses.classesId = this.dataForm.id
      if (this.teacherClasses.teacherId === '') {
        return this.$message.error('请选择教师')
      }
      addTeacherClasses(this.teacherClasses).then(res => {
        this.$message.success('添加成功')
        this.getTeacherClasses()
      })
    },
    handleUpdate: function() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dialogLoading = true
          update(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '修改成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleDelete(rowData) {
      this.$confirm('是否删除该用户？', '删除提示', { type: 'warning' })
        .then(() => {
          del(rowData)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '删除成功')
              this.getDataList()
            })
            .catch(err => {
              this.$message.error(err.msg || '删除失败')
              console.log(err)
            })
        })
        .catch(cancel => {
          console.log(cancel)
        })
    },
    handleTeacherDelete(rowData) {
      this.$confirm('是否删除该用户？', '删除提示', { type: 'warning' })
        .then(() => {
          this.teacherClasses.teacherId = rowData.id
          this.teacherClasses.classesId = this.dataForm.id
          delTeacherClasses(this.teacherClasses)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '删除成功')
              this.getTeacherClasses()
            })
            .catch(err => {
              this.$message.error(err.msg || '删除失败')
              console.log(err)
            })
        })
        .catch(cancel => {
          console.log(cancel)
        })
    }
  }
}
</script>
<style scoped>
.el-form .el-select {
  width: 100%;
}
</style>
